<template>
    <div class="page_container">
        <el-tabs v-model="activeName" @tab-click="tabChange">
            <el-tab-pane :label="`通知列表${tabsCount.noticeListNumTotal > 0 ? `(${tabsCount.noticeListNumTotal})` : ''}`" 
                name="0" :disabled="loading"></el-tab-pane>
            <el-tab-pane :label="`内容管理${tabsCount.contentNumTotal > 0 ? `(${tabsCount.contentNumTotal})` : ''}`" 
            name="1" :disabled="loading"></el-tab-pane>
        </el-tabs>
        <DataTableBar :data="tableData" :columns="columns" :config="config"
            :total="total" :pages="pages" :loading="loading"
            @search="search" @reset="searchReset" @refresh="refresh"
            @currentChange="currentChange" @sizeChange="sizeChange"
            @addBefore="addBefore" @editBefore="editBefore" @selectionChange="handleSelectionChange">
            <template v-slot:tableoper>
                <el-button type="danger" plain class="oper_button" @click="removeItems"
                    v-if="activeName == '1'">
                    <i class="icon-base icon-base-shanchu margin-right-sm"></i>删 除
                </el-button>
                <el-button plain class="oper_button" @click="setNoticeType">通知类型管理</el-button>
            </template>
            <template v-slot:noticeTitle="scope">
                <el-button link type="primary" @click="checkDetail(scope.row)">
                    {{ scope.row.noticeTitle }}
                    <span class="top_icon" v-if="scope.row.isTopStatus == 1 && activeName == '1'">置顶</span>
                </el-button>
            </template>
            <template v-slot:publishDate="scope">
                <span>{{ formatDate.dateTimeAllFormat( scope.row.publishDate || '') }}</span>
            </template>
            <template v-slot:noticeImportanceName="scope">
                <div class="flex space-around">
                    <span class="tag_icon important_icon" v-if="scope.row.isImportant">重要</span>
                    <span class="tag_icon urgent_icon" v-if="scope.row.isUrgent">紧急</span>
                    <span v-if="!scope.row.isImportant && !scope.row.isUrgent">-</span>
                </div>
            </template>
            <template v-slot:noticeUserTotal="scope">
                <p class="cursorPointer" @click="checkReadState(scope.row)">
                    <span>{{ scope.row.noticeUserTotal }}</span>
                    <span class="text-info margin-left-sm">( {{ scope.row.unReadNum }} )</span>
                </p>
            </template>
            <template v-slot:tablerow="scope">
                <el-divider direction="vertical" />
                <el-button type="primary" link @click="changeTopState(scope.row)">
                    {{ scope.row.isTopStatus == 1 ? '取消置顶' : '置 顶' }}
                </el-button>
            </template>
        </DataTableBar>
        <CreateNotice v-model:show="createNoticeDrawerShow" :defaultValue="selectrow" :state="operState"
            @submit="edit"></CreateNotice>
        <NoticeTypes v-model:show="noticeTypesDrawerShow"></NoticeTypes>
        <NoticeDetail v-model:show="noticeDetailDrawerShow" :data="selectrow"></NoticeDetail>
        <NoticeReadState v-model:show="noticeReadStateDialogShow" :data="selectrow"></NoticeReadState>
    </div>
</template>

<script setup>
    import { ref, onMounted } from "vue";
    import { noticePages, changeNoticeState, createNotice, editNotice, removeNotices, tabsStatistics } from "@/api/notice.js"
    import { ElMessage } from 'element-plus'
    import { formatDate } from "@/utils/fomart"
    import DataTableBar from "@/components/DataComponents/DataTableBar.vue"
    import CreateNotice from "./components/CreateNotice.vue"
    import NoticeTypes from "./components/NoticeTypes.vue"
    import NoticeDetail from "./components/NoticeDetail.vue"
    import NoticeReadState from "./components/NoticeReadState.vue"
    const { proxy } = getCurrentInstance();
    const activeName = ref('0');
    const createNoticeDrawerShow = ref(false);
    const noticeTypesDrawerShow = ref(false);
    const noticeDetailDrawerShow = ref(false);
    const noticeReadStateDialogShow = ref(false);
    const pages = ref({ page_current: 1, page_size: 10 });
    const total = ref(0);
    const loading = ref(false);
    const searchParams = ref({});
    const selectedRows = ref([]);
    const selectrow = ref({});
    const operState = ref(false);
    const tableData = ref([]);
    const tabsCount = ref({ contentNumTotal: 0, noticeListNumTotal: 0 });
    const columns = ref([
        { title: '标题',key: 'noticeTitle', search: true, tableCustom: true, },
        { title: '通知类型', key: 'noticeTypeName', width: 120, align: 'center',},
        { title: '重要程度',key: 'noticeImportanceName', width: 100, tableCustom: true, align: 'center',},
        { title: '通知类型', key: 'noticeTypeId', hide: true, search: true, searchType: 'dic', dicName: 'notification_type', },
        { title: '重要程度',key: 'noticeImportanceId', hide: true, search: true, searchType: 'dic', dicName: 'notification_importance', },
        { title: '通知人数/未读',key: 'noticeUserTotal', width: 120, align: 'center', tableCustom: true, },
        { title: '发布人',key: 'noticeSenderName', width: 100, },
        { title: '发布时间',key: 'publishDate', width: 160, tableCustom: true, },
    ]);
    const config = ref({
        addBtnText: '发通知',
        selection: false,
        rowOperHide: true,
        removeBtnHide: true,
        editCustom: true,
    });
    const addBefore = () => {
        operState.value = false;
        selectrow.value = {};
        createNoticeDrawerShow.value = true;
    };
    const editBefore = (rowData) => {
        operState.value = true;
        selectrow.value = rowData;
        createNoticeDrawerShow.value = true;
    };
    const edit = (formData) => {
        const submitData = dataReorganization(formData);
        if(operState.value){
            editNotice({
                ...submitData
            }).then(res => {
                createNoticeDrawerShow.value = false;
                ElMessage({ type: 'success', message: '通知修改成功', })
                getTablePages();
            });
            return
        }
        createNotice({
           ...submitData
        }).then(res => {
            createNoticeDrawerShow.value = false;
            ElMessage({ type: 'success', message: '通知发布成功', })
            getTablePages();
        });
    };
    // 数据重组
    const dataReorganization = (formData) => {
        if(formData.fileList && formData.fileList.length ){
            formData.fileListUrlList = formData.fileList.map( item => item.url );
        }
        let submitData = {
            id: formData.id || '',
            noticeTitle: formData.noticeTitle || '',
            noticeTypeId: formData.noticeTypeId || '',
            noticeContent: formData.noticeContent || '',
            noticeImportanceId: formData.noticeImportanceIdArr ? formData.noticeImportanceIdArr.toString() : '',
            isTopStatus: formData.isTopStatusArr ? formData.isTopStatusArr.toString() : '',
            receiverIds: formData.noticeObjectValues ? formData.noticeObjectValues.toString() : '',
            receiverNames: formData.receiverNames ? formData.receiverNames.toString() : '',
            attachUrls: formData.fileListUrlList ? formData.fileListUrlList.toString() : '',
        };
        submitData.asNoticeUsers = [];
        formData.noticeObjectValues.map( item => {
            const obj = { userId: item };
            submitData.asNoticeUsers.push(obj);
        });
        return submitData
    };
    const checkDetail = (rowData) => {
        selectrow.value = rowData;
        selectrow.value.managerType = activeName.value;
        noticeDetailDrawerShow.value = true;
    };
    const checkReadState = (rowData) => {
        selectrow.value = rowData;
        noticeReadStateDialogShow.value = true;
    };
    const setNoticeType = () => {
        noticeTypesDrawerShow.value = true;
    };
    const removeItems = () => {
        if(selectedRows.value.length <= 0){
            ElMessage({ type: 'warning', message: '请至少选择一项操作项', })
            return
        }
        const noticeTitles = selectedRows.value.map( item => item.noticeTitle);
        const noticeIds = selectedRows.value.map( item => item.id);
        proxy.$modal.confirm(`是否删除[ ${noticeTitles.toString()} ]等通知项吗？`).then(function() {
            removeNotices( noticeIds ).then(response => {
                proxy.$modal.msgSuccess("删除成功");
                getTablePages();
            });
        }).catch(() => {});
    };
    const handleSelectionChange = (rows) => {
        selectedRows.value = rows;
    };
    const tabChange = (value) => {
        activeName.value = value.paneName;
        pages.value.page_current = 1;
        config.value.selection = activeName.value == '1' ? true : false
        config.value.rowOperHide = activeName.value == '1' ? false : true
        getTablePages();
    };
    // 切换通知置顶状态
    const changeTopState = (row) => {
        changeNoticeState({
            id: row.id,
            isTopStatus: row.isTopStatus == '1' ? 0 : 1
        }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            getTablePages();
        });
    };
    const currentChange = (current) => {
        pages.value.page_current = current;
        getTablePages();
    };
    const sizeChange = (size) => {
        pages.value.page_size = size;
        getTablePages();
    };
    const refresh = (searchParam) => {
        searchParams.value = searchParam.value;
        getTablePages();
    };
    const search = (searchParam) => {
        searchParams.value = searchParam.value;
        getTablePages();
    }
    const searchReset = () => {
        searchParams.value = {};
        getTablePages();
    };
    const getTablePages = () => {
        loading.value = true;
        noticePages({
            current: pages.value.page_current,
            size: pages.value.page_size,
            managerType: activeName.value,
            ...searchParams.value
        }).then(res => {
            tableData.value = res.data.records || [];
            total.value = res.data.total;
            tableData.value.map( item => {
                item.noticeImportanceList = item.noticeImportanceName 
                    ? item.noticeImportanceName .split(',') : [];
                item.isImportant = item.noticeImportanceList.findIndex( item => item == '重要') >= 0 ? true : false;
                item.isUrgent = item.noticeImportanceList.findIndex( item => item == '紧急') >= 0 ? true : false;
            });
            loading.value = false;
        });
    };
    const getTabsCount = () => {
        tabsStatistics({}).then(res => {
            const resCount = res.data || {}
            for( const key in tabsCount.value){
                tabsCount.value[key] = resCount[key];
            }
        });
    };
    onMounted(() => {
        getTablePages();
        getTabsCount();
    })
</script>
<style scoped lang="scss">
    .top_icon{
        font-size: 12px;
        padding: 2px 4px;
        background-color: #999;
        margin-left: 10px;
        border-radius: 5px;
        color: #fff;
    }
    .tag_icon{
        padding: 0px 4px;
        font-size: 12px;
        border-radius: 3px;
    }
    .important_icon{ background-color: #F5222D;color: #fff; }
    .urgent_icon{  background-color: #F59A23;color: #fff; }
</style>